package com.itcast.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itcast.constant.RedisConstant;
import com.itcast.entity.PageResult;
import com.itcast.entity.QueryPageBean;
import com.itcast.mapper.SetmealMapper;
import com.itcast.pojo.Setmeal;
import com.itcast.untils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService{
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private JedisPool jedisPool;
    /**
     * 查询所有数据
     * @param queryPageBean
     */
    @Override
    public PageResult findAll(QueryPageBean queryPageBean) {
        //设置分页参数
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Setmeal> page = setmealMapper.findAll(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 添加数据
     * @param setmeal
     * @param checkgroupIds
     */
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealMapper.add(setmeal);
        //将数据存储到jedis
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        setSetmealandcheckgroup(setmeal.getId(),checkgroupIds);
    }
    //添加套餐表和检查组的关系
    public void setSetmealandcheckgroup(Integer setmeal_id,Integer[] checkgroupIds){
        if(checkgroupIds != null && checkgroupIds.length > 0){
            for (Integer checkgroup_id:checkgroupIds){
                Map<String,Integer> map = new HashMap<>();
                map.put("setmeal_id",setmeal_id);
                map.put("checkgroup_id",checkgroup_id);
                setmealMapper.addSetmealandCheckgroupp(map);
            }
        }
    }

    /**
     * 删除套餐
     * @param setmeal
     */
    @Override
    public void delete(Setmeal setmeal) {
        deleteSetmealandcheckgroup(setmeal.getId());
        setmealMapper.delete(setmeal.getId());
        deleteYun(setmeal);
    }

    /**
     * 删除关系
     * @param id
     */
    public void deleteSetmealandcheckgroup(Integer id){
        setmealMapper.deleteSetmealandcheckgroup(id);
    }
    public void deleteYun(Setmeal setmeal){
        //删除七牛云中的对应的图片
        QiniuUtils.deleteFileFromQiniu(setmeal.getImg());
    }

    /**
     * 查询套餐列表
     */
    @Override
    public List<Setmeal> getSetmeal() {
        return setmealMapper.getSetmeal();
    }

    /**
     * 查询单个套餐对象
     * @param id
     * @return
     */
    @Override
    public Setmeal findById(Integer id) {
        return setmealMapper.finById(id);
    }
}
